/*
 * @Author: wangtao
 * @Date: 2020-06-29 16:32:41
 * @LastEditors: kanglang
 * @LastEditTime: 2020-10-21 17:22:21
 * @Description: file content
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Modal,
  Text,
  TouchableOpacity,
  PixelRatio,
  ScrollView,
  Image,
  TextInput,
  KeyboardAvoidingView,
  Keyboard,
} from 'react-native';
import { number } from 'prop-types';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  fontColorDeepRed,
  fontColorBlack,
  fontColorLightGray,
  fontColorCoffee,
  screenWidth,
  px2dp,
  screenHeight,
  splitLineColorLightGray,
  fontColorSecDeepGray,
  mainBgColorBlack,
  fontColorDeepGray,
  fontColorLightCoffee,
} from '../../../../../common/styles';
import { Button, DashLine, msg } from '../../../../../common';
import { iconUpdate } from '../../../../../image';
import { fetchPackagingTypes } from '../../../../../api/source-release';
import SelectItem from './select-item';

const { Submit } = Button;

export default class SourceInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      supplyName: null,
      supplyTypeOneId: null,
      supplyTypeOneName: null,
      supplyTypeTwoId: null,
      supplyTypeTwoName: null,
      packagingType: [], // 选择的打包类型 暂存为数组
      weight: '', // 货物重量  暂存为数组
      packagingTypes: [], // 供选择的打包类型
      twoTree: [],
      isSubmit: false,
      keyboardHeight: '', // 键盘高度
    };
  }

  componentDidMount() {
    const { supply, treeList } = this.props;

    const {
      supplyName,
      weight,
      supplyTypeTwoId,
      packagingType,
      supplyTypeOneId,
      supplyTypeOneName,
      supplyTypeTwoName
    } = supply;
    const supplyOneId = supplyTypeOneId || treeList[0].id;
    const supplyOneName = supplyTypeOneName || treeList[0].name;

    const supplyTwoId = supplyTypeTwoId || treeList[1].id;
    const supplyTwoName = supplyTypeTwoName || treeList[1].name;
    this.setState({
      supplyTypeOneId: supplyOneId,
      supplyTypeOneName: supplyOneName,
      supplyName,
      weight,
      supplyTypeTwoId: supplyTwoId,
      supplyTypeTwoName: supplyTwoName
    });
    if (packagingType != null || packagingType != undefined) {
      this.setState({ packagingType: [packagingType] });
    }
    this.calcTree(treeList, supplyOneId);
    if (supplyTypeTwoId != null) {
      fetchPackagingTypes({ typeId: supplyTypeTwoId }).then((res) => {
        if (res.success) {
          this.setState({ packagingTypes: res.data });
        }
      });
    }

    // 监听键盘
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardWillShow',
      this._keyboardDidShow.bind(this),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      this._keyboardDidHide.bind(this),
    );
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  render() {
    const { onChangeModal, sourceInfoType, supply, treeList } = this.props;
    const {
      supplyTypeOneId,
      supplyTypeTwoId,
      twoTree,
      supplyName,
      supplyTypeOneName,
      supplyTypeTwoName,
      packagingTypes,
      packagingType,
      isSubmit,
      weight,
    } = this.state;

    return (
      <Modal
        animationType='slide'
        transparent
        visible
        onRequestClose={() => {
          onChangeModal({ type: 'sourceInfoIsShow', val: false });
          // msg.emit('router: back');
        }}
        onShow={() => { }}
      >

        <TouchableOpacity
          style={styles.mask}
          onPress={() => {
            onChangeModal({ type: 'sourceInfoIsShow', val: false });
            if (!weight) {
              onChangeModal({
                type: 'sourceInfoType',
                val: 'add',
              });
            }
          }}
        />

        <View
          style={[
            styles.infoContainer,
            { paddingBottom: Number(this.state.keyboardHeight) + 10 },
          ]}
        >
          <View style={styles.header}>
            <TouchableOpacity
              style={styles.cancel}
              onPress={() => {
                onChangeModal({ type: 'sourceInfoIsShow', val: false });
                if (!weight) {
                  onChangeModal({
                    type: 'sourceInfoType',
                    val: 'add',
                  });
                }
              }}
            >
              <Text style={{ fontSize: px2dp(32), color: fontColorSecDeepGray }}>
                取消
              </Text>
            </TouchableOpacity>
            <Text
              style={{
                fontSize: px2dp(32),
                color: fontColorBlack,
                fontWeight: 'bold',
              }}
            >
              货物信息
            </Text>
            {sourceInfoType === 'edit' && (
              <Submit
                text='确定'
                boxStyle={{
                  width: px2dp(104),
                  height: px2dp(60),
                  borderRadius: px2dp(8),
                  position: 'absolute',
                  right: px2dp(28),
                }}
                disabled={false}
                onClick={() => {
                  this.submit();
                }}
              />
            )}
          </View>

          {/* 类别 */}
          {sourceInfoType === 'add' && (
            <View style={styles.listContainer}>
              <ScrollView
                style={{
                  width: px2dp(300),
                  maxHeight: 0.8 * screenHeight,
                  backgroundColor: mainBgColorLightGray,
                }}
                showsVerticalScrollIndicator={false}
              >
                <View style={styles.leftMenu}>
                  {!!treeList &&
                    treeList.map((item) => {
                      return (
                        <TouchableOpacity
                          style={styles.leftMenuItem}
                          key={item.id}
                          onPress={() => {
                            this.setState({ supplyTypeOneId: item.id });
                            this.setState({
                              supplyTypeOneName: item.name,
                            });
                            this.calcTree(treeList, item.id);
                          }}
                        >
                          <Text
                            style={[
                              styles.itemtext,
                              supplyTypeOneId === item.id
                                ? { color: fontColorCoffee }
                                : {},
                            ]}
                          >
                            {item.name}
                          </Text>
                        </TouchableOpacity>
                      );
                    })}
                </View>
              </ScrollView>
              <ScrollView
                style={{
                  width: screenWidth - px2dp(300),
                  maxHeight: 0.8 * screenHeight,
                }}
                showsVerticalScrollIndicator={false}
              >
                <View style={styles.rightMenu}>
                  {!!twoTree &&
                    twoTree.map((item) => {
                      return (
                        <TouchableOpacity
                          style={styles.rightMenuItem}
                          key={item.id}
                          onPress={() => {
                            this.setState({ supplyTypeTwoId: item.id });
                            this.setState({
                              supplyTypeTwoName: item.name,
                              supplyName: `${supplyTypeOneName}-${item.name}`,
                            });
                            onChangeModal({
                              type: 'sourceInfoType',
                              val: 'edit',
                            });
                            fetchPackagingTypes({ typeId: item.id }).then(
                              (res) => {
                                if (res.success) {
                                  this.setState({ packagingTypes: res.data });
                                  if (
                                    res.data.length != 0 &&
                                    this.state.packagingType.length == 0
                                  ) {
                                    this.setState({
                                      packagingType: [res.data[0].name],
                                    });
                                  }
                                }
                              },
                            );
                          }}
                        >
                          <Text style={styles.itemtext}>{item.name}</Text>
                        </TouchableOpacity>
                      );
                    })}
                </View>
              </ScrollView>
            </View>
          )}

          {/* 编辑 */}
          {sourceInfoType === 'edit' && (
            <ScrollView showsVerticalScrollIndicator={false}>
              <View style={styles.editContainer}>
                <View style={styles.title}>
                  <View
                    style={{
                      flex: 1,
                      justifyContent: 'center',
                      alignItems: 'center',
                      marginLeft: px2dp(60) * 2,
                    }}
                  >
                    <Text
                      numberOfLines={1}
                      style={{
                        fontSize: px2dp(36),
                        fontWeight: 'bold',
                        color: mainBgColorBlack,
                        marginRight: px2dp(100),
                      }}
                    >
                      {supplyName}
                    </Text>
                  </View>
                  <TouchableOpacity
                    style={[styles.update]}
                    onPress={() => {
                      onChangeModal({
                        type: 'sourceInfoType',
                        val: 'add',
                      });
                    }}
                  >
                    <Image
                      style={[styles.dotImg]}
                      resizeMode='contain'
                      source={iconUpdate}
                    />
                    <Text
                      style={{
                        fontSize: px2dp(28),
                        color: fontColorSecDeepGray,
                      }}
                    >
                      更改
                    </Text>
                  </TouchableOpacity>
                </View>
                <DashLine />
                {/* 包装方式 */}
                <View style={styles.packing}>
                  <Text
                    style={{
                      fontSize: px2dp(28),
                      fontWeight: 'bold',
                      color: mainBgColorBlack,
                    }}
                  >
                    包装方式
                  </Text>
                  <View style={styles.packingSelect}>
                    {!!packagingTypes &&
                      packagingTypes.map((item) => {
                        return (
                          <SelectItem
                            name={item.name}
                            type='packagingType'
                            value={item.name}
                            activeVal={packagingType}
                            // maxLength={1}
                            onChange={(type, value) =>
                              this.onChange(type, value)}
                          />
                        );
                      })}
                  </View>
                </View>

                {/* 货重 */}
                <View style={styles.packing}>
                  <Text
                    style={{
                      fontSize: px2dp(28),
                      fontWeight: 'bold',
                      color: mainBgColorBlack,
                    }}
                  >
                    货重
                    {' '}
                    <Text
                      style={{
                        fontSize: px2dp(28),
                        fontWeight: 'normal',
                        color:
                          !isSubmit || weight ? fontColorSecDeepGray : 'red',
                      }}
                    >
                      (必填，单位: 吨)
                    </Text>
                  </Text>
                  <View style={styles.weightSelect}>
                    <TextInput
                      placeholder='请输入货物重量'
                      maxLength={3}
                      style={[
                        styles.goodsWrapPriceTextInput,
                        { color: fontColorBlack },
                      ]}
                      defaultValue={weight}
                      value={weight}
                      underlineColorAndroid='transparent'
                      onChangeText={(text) => {
                        this.onChangeWeight(text, 0);
                      }}
                      keyboardType={
                        Platform.OS === 'android' ? 'numeric' : 'decimal-pad'
                      }
                      onBlur={() => { }}
                    />
                    <Text style={{ color: fontColorDeepGray }}>吨</Text>
                  </View>
                </View>
              </View>
            </ScrollView>
          )}
        </View>
      </Modal>
    );
  }

  _keyboardDidShow(e) {
    this.setState({
      keyboardHeight: e.startCoordinates.height,
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0,
    });
  }

  // 改变
  onChange = (type, val) => {
    this.setState({ [type]: val });
  };

  // 修改重量
  onChangeWeight = (val, flag) => {
    // var reg1=/^[1-9]\d{0,2}$/;
    // if(!reg1.test(val)) return;
    const { weight } = this.state;
    if (/\D/g.test(val)) {
      const val1 = val.replace(/\D/g, '');
      this.setState({ weight: val1 });
      return;
    }
    this.setState({ weight: val });
  };

  // 提交
  submit = () => {
    const {
      supplyName,
      supplyTypeOneId,
      supplyTypeOneName,
      supplyTypeTwoId,
      supplyTypeTwoName,
      packagingType,
      weight,
    } = this.state;
    if (!weight) {
      this.setState({ isSubmit: true });
      return;
    }

    const { onChangeModal, onChangeVal } = this.props;

    onChangeVal({
      type: 'supply',
      val: {
        supplyName,
        supplyTypeOneId,
        supplyTypeOneName,
        supplyTypeTwoId,
        supplyTypeTwoName,
        packagingType: packagingType.join(),
        weight,
      },
    });
    onChangeModal({ type: 'sourceInfoIsShow', val: false });
  };

  // 过滤得到子树
  calcTree = (treeList, supplyTypeOneId) => {
    const tree = treeList.filter((item) => {
      if (item.id === supplyTypeOneId) {
        return item.children;
      }
    });

    this.setState({ twoTree: tree.length ? tree[0].children : [] });
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
  },
  mask: {
    width: screenWidth,
    height: screenHeight,
    backgroundColor: 'rgba(0,0,0,0.2)',
    position: 'absolute',
    left: 0,
    top: 0,
  },
  infoContainer: {
    width: screenWidth,
    maxHeight: 0.8 * screenHeight,
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    bottom: 0,
    left: 0,
    borderRadius: px2dp(12),
    overflow: 'hidden',
    zIndex: 10,
  },
  header: {
    width: screenWidth,
    height: px2dp(108),
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderColor: splitLineColorLightGray,
    paddingHorizontal: px2dp(48),
  },
  cancel: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 80,
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  listContainer: {
    // paddingVertical: px2dp(16),
    flexDirection: 'row',
  },
  editContainer: {
    padding: px2dp(32),
    paddingBottom: px2dp(100),
  },
  item: {
    width: '100%',
    height: px2dp(92),
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    width: '100%',
    height: px2dp(92),
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
  },
  dotImg: {
    width: px2dp(24),
    height: px2dp(24),
  },
  update: {
    position: 'absolute',
    right: 0,
    flexDirection: 'row',
    alignItems: 'center',
  },
  packing: {
    marginTop: px2dp(48),
  },
  packingSelect: {
    marginTop: px2dp(24),
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
  },
  selectItem: {
    width: px2dp(218),
    height: px2dp(72),
    backgroundColor: mainBgColorLightGray,
    borderRadius: px2dp(8),
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: px2dp(16),
    marginRight: px2dp(10),
  },
  goodsWrapPriceTextInput: {
    fontSize: px2dp(28),
    height: px2dp(72),
    // width: px2dp(296),
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    // textAlign: 'center',
    paddingTop: 0,
    paddingBottom: 0,
  },
  weightSelect: {
    marginTop: px2dp(24),
    paddingHorizontal: px2dp(24),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
  },
  itemtext: {
    color: fontColorDeepGray,
    fontSize: px2dp(28),
  },
  leftMenu: {
    backgroundColor: mainBgColorLightGray,
    paddingBottom: px2dp(180),
    width: px2dp(300),
  },
  rightMenu: {
    backgroundColor: mainBgColorWhite,
    paddingBottom: px2dp(180),
    flex: 1,
  },
  leftMenuItem: {
    width: '100%',
    height: px2dp(92),
    justifyContent: 'center',
    alignItems: 'center',
  },
  rightMenuItem: {
    height: px2dp(92),
    justifyContent: 'center',
    alignItems: 'center',
  },
});
